<template>
  <div class="category-management">
    <!-- 顶部操作栏 -->
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>添加分类
      </el-button>
    </div>

    <!-- 分类列表 -->
    <el-table
      v-loading="loading"
      :data="categories"
      style="width: 100%"
      row-key="_id"
      :default-sort="{ prop: 'order', order: 'ascending' }"
    >
      <el-table-column label="图标" width="80" align="center">
        <template #default="{ row }">
          <el-icon>
            <component :is="row.icon || 'Folder'" />
          </el-icon>
        </template>
      </el-table-column>

      <el-table-column label="分类名称" prop="name" min-width="200">
        <template #default="{ row }">
          <div class="category-info">
            <span class="name">{{ row.name }}</span>
            <span class="path">/category/{{ row.path }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="视频数量" width="120" align="center" prop="videoCount" sortable />

      <el-table-column label="排序" width="120" align="center" prop="order" sortable />

      <el-table-column label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 'active' ? 'success' : 'info'">
            {{ row.status === 'active' ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <el-button
              type="primary"
              link
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              :type="row.status === 'active' ? 'danger' : 'success'"
              link
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete(row)"
              :disabled="row.videoCount > 0"
            >
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editingCategory._id ? '编辑分类' : '添加分类'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="editingCategory"
        :rules="categoryRules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="editingCategory.name" />
        </el-form-item>

        <el-form-item label="路径" prop="path">
          <el-input v-model="editingCategory.path">
            <template #prepend>/category/</template>
          </el-input>
        </el-form-item>

        <el-form-item label="图标" prop="icon">
          <el-select v-model="editingCategory.icon" placeholder="选择图标">
            <el-option
              v-for="icon in availableIcons"
              :key="icon"
              :label="icon"
              :value="icon"
            >
              <el-icon>
                <component :is="icon" />
              </el-icon>
              <span style="margin-left: 8px">{{ icon }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="排序" prop="order">
          <el-input-number v-model="editingCategory.order" :min="0" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="editingCategory.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="editingCategory.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import {
  Plus,
  Folder,
  VideoCamera,
  Headset,
  Trophy,
  Reading,
  Film,
  Compass,
  Basketball,
  Monitor,
  ChatDotRound
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import http from '@/services/axios.js' // 确认导入的是配置好的实例
import { formatDate } from '@/utils/formatters.js'

// 可用图标列表
const availableIcons = [
  'Folder',
  'VideoCamera',
  'Headset',
  'Trophy',
  'Reading',
  'Film',
  'Compass',
  'Basketball',
  'Monitor',
  'ChatDotRound'
]

// 表格数据
const categories = ref([])
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const formRef = ref(null)
const saving = ref(false)
const editingCategory = ref({
  name: '',
  path: '',
  icon: '',
  order: 0,
  status: 'active',
  description: ''
})

// 表单验证规则
const categoryRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入路径', trigger: 'blur' },
    { pattern: /^[a-z0-9-]+$/, message: '路径只能包含小写字母、数字和连字符', trigger: 'blur' }
  ],
  icon: [
    { required: true, message: '请选择图标', trigger: 'change' }
  ],
  order: [
    { required: true, message: '请输入排序', trigger: 'blur' },
    { type: 'number', message: '排序必须为数字', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取分类列表
const fetchCategories = async () => {
  loading.value = true
  try {
    // 修改为管理员专用接口路径
    const response = await http.get('/api/admin/categories', {
      params: { page: 1, limit: 100 } // 暂时获取所有分类，或实现分页
    })
    // 修改响应数据处理方式
    categories.value = response.data.categories || response.data || []
    // 如果后端返回了 totalCategories，可以用于分页
    // total.value = response.data.totalCategories
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  } finally {
    loading.value = false
  }
}

// 保存分类（创建或更新）
const handleSave = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true
      try {
        if (editingCategory.value._id) {
          // 更新现有分类
          await http.put(`/api/categories/${editingCategory.value._id}`, editingCategory.value)
          ElMessage.success('分类更新成功')
        } else {
          // 创建新分类
          await http.post('/api/categories', editingCategory.value)
          ElMessage.success('分类创建成功')
        }
        dialogVisible.value = false
        fetchCategories() // 刷新列表
      } catch (error) {
        console.error('保存分类失败:', error)
        ElMessage.error('保存分类失败')
      } finally {
        saving.value = false
      }
    }
  })
}

// 切换分类状态
const handleToggleStatus = async (category) => {
  try {
    const newStatus = category.status === 'active' ? 'disabled' : 'active'
    await http.patch(`/api/categories/${category._id}/status`, { status: newStatus })
    category.status = newStatus
    ElMessage.success(`分类已${newStatus === 'active' ? '启用' : '禁用'}`)
  } catch (error) {
    console.error('更新分类状态失败:', error)
    ElMessage.error('更新分类状态失败')
  }
}

// 删除分类
const handleDelete = async (category) => {
  try {
    await ElMessageBox.confirm(`确定要删除分类 "${category.name}" 吗？`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // 检查是否有视频或帖子关联此分类 (前端校验，后端也应有校验)
    if (category.videoCount > 0) { // 假设 videoCount 字段存在
      ElMessage.warning('该分类下还有内容，无法删除')
      return
    }
    await http.delete(`/api/categories/${category._id}`)
    ElMessage.success('删除成功')
    // 从列表中移除
    const index = categories.value.findIndex(c => c._id === category._id)
    if (index !== -1) {
      categories.value.splice(index, 1)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除分类失败:', error)
      // 检查是否是后端返回的特定错误消息
      if (error.response?.data?.message) {
        ElMessage.error(error.response.data.message)
      } else {
        ElMessage.error('删除分类失败')
      }
    }
  }
}

// 添加分类
const handleAdd = () => {
  editingCategory.value = {
    name: '',
    path: '',
    icon: '',
    order: categories.value.length,
    status: 'active',
    description: ''
  }
  dialogVisible.value = true
}

// 编辑分类
const handleEdit = (category) => {
  editingCategory.value = { ...category }
  dialogVisible.value = true
}

// 初始化
onMounted(() => {
  fetchCategories()
})
</script>

<style scoped>
.category-management {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
}

.category-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.path {
  font-size: 13px;
  color: #909399;
}

.el-icon {
  font-size: 20px;
  vertical-align: middle;
}

/* 图标选择器样式 */
.el-select-dropdown__item {
  display: flex;
  align-items: center;
}

.el-select-dropdown__item .el-icon {
  margin-right: 8px;
}
</style>